<template>
  <div class="study-record-container">
    <el-card class="timer-card">
      <div class="timer-display">
        <h2>学习计时器</h2>
        <div class="time">{{ formatTime(timer) }}</div>
      </div>
      
      <div class="timer-controls">
        <el-button 
          type="primary" 
          :disabled="isRunning"
          @click="startTimer"
          size="large"
        >
          <el-icon><VideoPlay /></el-icon>
          开始学习
        </el-button>
        
        <el-button 
          type="danger" 
          :disabled="!isRunning"
          @click="stopTimer"
          size="large"
        >
          <el-icon><VideoPause /></el-icon>
          结束学习
        </el-button>
      </div>

      <div class="study-stats" v-if="statistics">
        <el-divider>学习统计</el-divider>
        <div class="stats-content">
          <div class="stat-item">
            <div class="stat-value">{{ formatDuration(statistics.total_time) }}</div>
            <div class="stat-label">总学习时长</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ formatDuration(statistics.average_time) }}</div>
            <div class="stat-label">平均时长</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ statistics.total_records }}</div>
            <div class="stat-label">学习次数</div>
          </div>
        </div>
      </div>
    </el-card>

    <el-dialog
      v-model="showSaveDialog"
      title="保存学习记录"
      width="500px"
    >
      <el-form 
        ref="recordFormRef"
        :model="recordForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="学习阶段" prop="category">
          <el-select 
            v-model="recordForm.category" 
            placeholder="请选择学习阶段"
            style="width: 100%"
          >
            <el-option label="小学" value="primary" />
            <el-option label="初中" value="junior" />
            <el-option label="高中" value="senior" />
            <el-option label="大学" value="university" />
            <el-option label="在职" value="working" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="学习内容" prop="notes">
          <el-input
            v-model="recordForm.notes"
            type="textarea"
            :rows="4"
            placeholder="记录一下今天学习的内容..."
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showSaveDialog = false">取消</el-button>
          <el-button type="primary" @click="saveRecord">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-card class="records-card">
      <template #header>
        <div class="records-header">
          <h3>学习记录</h3>
          <el-button type="primary" @click="loadRecords" :icon="Refresh">
            刷新
          </el-button>
        </div>
      </template>
      
      <el-table :data="records" style="width: 100%" v-loading="loading">
        <el-table-column prop="start_time" label="开始时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.start_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="时长" width="120">
          <template #default="scope">
            {{ formatDuration(scope.row.duration) }}
          </template>
        </el-table-column>
        <el-table-column prop="category" label="学习阶段" width="120">
          <template #default="scope">
            <el-tag :type="getCategoryType(scope.row.category)">
              {{ getCategoryLabel(scope.row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="notes" label="学习内容" show-overflow-tooltip />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button 
              type="danger" 
              size="small" 
              @click="deleteRecord(scope.row.id)"
              :icon="Delete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { VideoPlay, VideoPause, Refresh, Delete } from '@element-plus/icons-vue'
import axios from 'axios'

const store = useStore()
const timer = ref(0)
const isRunning = ref(false)
const startTime = ref(null)
const timerInterval = ref(null)
const showSaveDialog = ref(false)
const recordFormRef = ref(null)
const records = ref([])
const loading = ref(false)
const statistics = ref(null)

const recordForm = ref({
  category: '',
  notes: '',
})

const rules = {
  category: [
    { required: true, message: '请选择学习阶段', trigger: 'change' }
  ]
}

// 开始计时
const startTimer = () => {
  isRunning.value = true
  startTime.value = new Date()
  timerInterval.value = setInterval(() => {
    timer.value++
  }, 1000)
}

// 停止计时
const stopTimer = () => {
  clearInterval(timerInterval.value)
  isRunning.value = false
  showSaveDialog.value = true
}

// 保存记录
const saveRecord = async () => {
  if (!recordFormRef.value) return
  
  await recordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const data = {
          user: store.state.user.id,
          start_time: startTime.value.toISOString(),
          duration: timer.value,
          category: recordForm.value.category,
          notes: recordForm.value.notes
        }
        
        const response = await axios.post('/api/study/records/', data)
        
        if (response.status === 201) {
          ElMessage.success('记录保存成功')
          showSaveDialog.value = false
          timer.value = 0
          recordForm.value = { category: '', notes: '' }
          loadRecords()
          loadStatistics()
        }
      } catch (error) {
        ElMessage.error('保存失败：' + (error.response?.data?.message || error.message))
      }
    }
  })
}

// 加载记录列表
const loadRecords = async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/study/records/')
    records.value = response.data
  } catch (error) {
    ElMessage.error('加载记录失败')
  } finally {
    loading.value = false
  }
}

// 加载统计数据
const loadStatistics = async () => {
  try {
    const response = await axios.get('/api/study/statistics/')
    statistics.value = response.data
  } catch (error) {
    ElMessage.error('加载统计数据失败')
  }
}

// 删除记录
const deleteRecord = async (id) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条学习记录吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await axios.delete(`/api/study/records/${id}/`)
    ElMessage.success('删除成功')
    loadRecords()
    loadStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + error.message)
    }
  }
}

// 格式化时间显示
const formatTime = (seconds) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 格式化日期显示
const formatDate = (dateStr) => {
  const date = new Date(dateStr)
  return date.toLocaleString()
}

// 格式化时长显示
const formatDuration = (seconds) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  return `${hours}小时${minutes}分钟`
}

// 获取类别标签
const getCategoryLabel = (category) => {
  const labels = {
    primary: '小学',
    junior: '初中',
    senior: '高中',
    university: '大学',
    working: '在职'
  }
  return labels[category] || category
}

// 获取类别标签样式
const getCategoryType = (category) => {
  const types = {
    primary: 'success',
    junior: 'info',
    senior: 'warning',
    university: 'primary',
    working: 'danger'
  }
  return types[category] || 'info'
}

onMounted(() => {
  loadRecords()
  loadStatistics()
})
</script>

<style scoped>
.study-record-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.timer-card {
  margin-bottom: 20px;
  text-align: center;
}

.timer-display {
  margin-bottom: 30px;
}

.timer-display h2 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 15px;
}

.time {
  font-size: 64px;
  font-weight: bold;
  color: #409EFF;
  font-family: monospace;
  text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
}

.timer-controls {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-bottom: 20px;
}

.study-stats {
  margin-top: 20px;
}

.stats-content {
  display: flex;
  justify-content: center;
  gap: 40px;
  margin-top: 20px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.stat-label {
  color: #909399;
  margin-top: 5px;
}

.records-card {
  margin-top: 20px;
}

.records-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.records-header h3 {
  margin: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-table) {
  margin-top: 15px;
}
</style> 